package cn.lger.icollege.util.excel;

import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.Iterator;

/**
 * Code that Changed the World
 * Pro said
 * Created by Pro on 2018-04-29.
 */
public class ExcelUtil {

    /**
     * 读取Excel表格，并且每一行数据除了头字段都通过ExcelDealReadRow处理
     * @param sheetIndex 表的下标
     * @param excelFile Excel文件
     * @param headers Excel字段
     * @param readRow ExcelDealReadRow
     * @throws IOException IOException
     * @throws InvalidFormatException InvalidFormatException
     */
    public static void readExcelDealRow(Integer sheetIndex, File excelFile, String[] headers, ExcelDealReadRow readRow) throws IOException, InvalidFormatException {

        InputStream inputStream = new FileInputStream(excelFile);
        Workbook workbook = WorkbookFactory.create(inputStream);
        if (sheetIndex == null || sheetIndex < 0){
            sheetIndex = 0;
        }
        Sheet sheet = workbook.getSheetAt(sheetIndex);
        Row row = sheet.getRow(0);
        Iterator<Cell> cellIterator = row.cellIterator();
        int i = 0;
        while (cellIterator.hasNext()){
            Cell cell = cellIterator.next();
            if (i >= headers.length){
                throw new RuntimeException("Excel的字段名不符合要求："+ Arrays.toString(headers));
            } else if (!headers[i].equals(cell.getStringCellValue())){
                throw new RuntimeException("Excel的"+cell.getStringCellValue()+"字段不符合要求,应改为："+ headers[i]);
            }
            i++;
        }
        sheet.removeRow(row);

        Iterator<Row> rowIterator = sheet.rowIterator();
        while (rowIterator.hasNext()){
            row = rowIterator.next();
            readRow.readOneRow(row);
        }

    }

    public static Workbook writeRowToExcel(String sheetName, ExcelDealWriteHeaders writeHeaders, ExcelDealWriteRow dealWriteRow){
        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet(sheetName);
        Row row = sheet.createRow(0);
        writeHeaders.writeHeaders(row);
        int i = 0;
        while (dealWriteRow.writeRow(sheet.createRow(i+1), i)){
            i++;
        }
        return workbook;
    }

    /**
     * 获取Excel中一个单元格的数据返回为String类型
     * @param cell cell
     * @return String
     */
    public static String getCellValue(Cell cell) {
        if (cell == null){
            return null;
        }
        switch (cell.getCellType()) {
            case Cell.CELL_TYPE_STRING:
                return cell.getStringCellValue();
            case Cell.CELL_TYPE_NUMERIC:
                return Integer.toString((int) cell.getNumericCellValue());
            default:
                return "";
        }
    }

}
